package com.myc.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.myc.subject.common.entity.PageResult;
import com.myc.subject.common.enums.IsDeletedFlagCodeEnum;
import com.myc.subject.common.util.IdWorkerUtil;
import com.myc.subject.common.util.LoginUtil;
import com.myc.subject.domain.convert.SubjectInfoConverter;
import com.myc.subject.domain.entity.SubjectInfoBO;
import com.myc.subject.domain.entity.SubjectOptionBO;
import com.myc.subject.domain.handle.subject.SubjectTypeHandler;
import com.myc.subject.domain.handle.subject.SubjectTypeHandlerFactory;
import com.myc.subject.domain.redis.RedisUtil;
import com.myc.subject.domain.service.SubjectInfoDomainService;
import com.myc.subject.domain.service.SubjectLikedDomainService;
import com.myc.subject.infra.basic.entity.SubjectInfo;
import com.myc.subject.infra.basic.entity.SubjectInfoEs;
import com.myc.subject.infra.basic.entity.SubjectLabel;
import com.myc.subject.infra.basic.entity.SubjectMapping;
import com.myc.subject.infra.basic.service.SubjectEsService;
import com.myc.subject.infra.basic.service.SubjectInfoService;
import com.myc.subject.infra.basic.service.SubjectLabelService;
import com.myc.subject.infra.basic.service.SubjectMappingService;
import com.myc.subject.infra.entity.UserInfo;
import com.myc.subject.infra.rpc.UserRPC;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {


    @Resource
    private SubjectInfoService subjectInfoService;
    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;
    @Resource
    private SubjectMappingService subjectMappingService;
    @Resource
    private SubjectLabelService subjectLabelService;
    @Resource
    private SubjectEsService subjectEsService;

    @Resource
    private UserRPC userRPC;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;

    private static final String RANK_KEY = "subject_rank";
    /***
     * 新增题目
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SubjectInfoBO subjectInfoBO) {

        if(log.isInfoEnabled()){
            log.info("SubjectInfoDomainServiceImpl.add.bo:{}", JSON.toJSONString(subjectInfoBO));
        }
        //新增主表信息
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBoToInfo(subjectInfoBO);
        subjectInfo.setIsDeleted(IsDeletedFlagCodeEnum.UN_DELETED.getCode());
        subjectInfoService.insert(subjectInfo);
        //工厂插入
        SubjectTypeHandler hander = subjectTypeHandlerFactory.getHander(subjectInfo.getSubjectType());
        subjectInfoBO.setId(subjectInfo.getId());
        hander.add(subjectInfoBO);
        //新增对应的SubjectMapping信息
        List<Integer> categoryIds = subjectInfoBO.getCategoryIds();
        List<Integer> labelIds = subjectInfoBO.getLabelIds();
        List<SubjectMapping> subjectMappingList = new LinkedList<>();
        categoryIds.forEach( categoryId -> {
            labelIds.forEach( labelId -> {
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setSubjectId(subjectInfo.getId());
                subjectMapping.setCategoryId(Long.valueOf(categoryId));
                subjectMapping.setLabelId(Long.valueOf(labelId));
                subjectMapping.setIsDeleted(IsDeletedFlagCodeEnum.UN_DELETED.getCode());
                subjectMappingList.add(subjectMapping);
            });
        });
        subjectMappingService.batchInsert(subjectMappingList);
        //将题目信息放入es
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setDocId(new IdWorkerUtil(1,1,1).nextId());
        subjectInfoEs.setSubjectId(subjectInfo.getId());
        subjectInfoEs.setSubjectAnswer(subjectInfoBO.getSubjectAnswer());
        subjectInfoEs.setCreateTime(new Date().getTime());
        subjectInfoEs.setCreateUser("测试");
        subjectInfoEs.setSubjectName(subjectInfo.getSubjectName());
        subjectInfoEs.setSubjectType(subjectInfo.getSubjectType());
        subjectEsService.insert(subjectInfoEs);
        //将题目信息放入redis排行榜
        redisUtil.addScore(RANK_KEY, LoginUtil.getLoginId(),1);
    }

    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        //构造分页的实体
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        pageResult.setPageSize(subjectInfoBO.getPageSize());
        int start = (subjectInfoBO.getPageNo() - 1) * subjectInfoBO.getPageSize();
        //转化
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBoToInfo(subjectInfoBO);
        //查询列表数量
        int count = subjectInfoService.countByCondition(subjectInfo, subjectInfoBO.getCategoryId(), subjectInfoBO.getLabelId());
        if(count == 0){
            return pageResult;
        }
        //查询列表数据
        List<SubjectInfo> subjectInfos = subjectInfoService.queryPage(subjectInfo, subjectInfoBO.getCategoryId(),
                subjectInfoBO.getLabelId(), start, subjectInfoBO.getPageSize());
        List<SubjectInfoBO> subjectInfoBOS = SubjectInfoConverter.INSTANCE.convertListInfoToBO(subjectInfos);

        //组装数据
        pageResult.setRecords(subjectInfoBOS);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        //根据ID获取数据
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());
        //策略模式获取对应题目详细信息
        SubjectTypeHandler hander = subjectTypeHandlerFactory.getHander(subjectInfo.getSubjectType());
        SubjectOptionBO optionBO = hander.query(subjectInfoBO.getId().intValue());
        //转换类型
        SubjectInfoBO bo = SubjectInfoConverter.INSTANCE.convertOptionAndInfoToBo(optionBO, subjectInfo);


        //构造SubjectMapping
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfo.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagCodeEnum.UN_DELETED.getCode());
        //查询数据
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        //过滤出label的id列表
        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        //根据id查询列表信息
        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
        //过滤出labelname
        List<String> labelNameList = labelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());

        bo.setLabelName(labelNameList);
        //获取点赞信息
        bo.setLiked(subjectLikedDomainService.isLiked(subjectInfoBO.getId().toString(),LoginUtil.getLoginId()));
        bo.setLikedCount(subjectLikedDomainService.getLikedCount(subjectInfoBO.getId().toString()));

        return bo;
    }

    @Override
    public PageResult<SubjectInfoEs> getSubjectPageBySearch(SubjectInfoBO subjectInfoBO) {
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setPageNo(subjectInfoBO.getPageNo());
        subjectInfoEs.setPageSize(subjectInfoBO.getPageSize());
        subjectInfoEs.setKeyWord(subjectInfoBO.getKeyWord());
        return subjectEsService.querySubjectList(subjectInfoEs);
    }

    @Override
    public List<SubjectInfoBO> getContributeList() {
        //查询数据
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if (log.isInfoEnabled()){
            log.info("getContributeList.typedTuples:{]",JSON.toJSONString(typedTuples));
        }
        //判断为空
        if (CollectionUtils.isEmpty(typedTuples)){
            return Collections.emptyList();
        }
        List<SubjectInfoBO> boList = new LinkedList<>();
        //不为空
        typedTuples.forEach(rank -> {
            //构造返回的bo对象
            SubjectInfoBO subjectInfoBO = new SubjectInfoBO();
            //构造对象数据
            subjectInfoBO.setSubjectCount(rank.getScore().intValue());
            UserInfo userInfo = userRPC.getUserInfo(rank.getValue());
            subjectInfoBO.setCreateUser(userInfo.getNickName());
            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
            boList.add(subjectInfoBO);
        });
        return boList;
    }


}
